package com.example.design.shejimoshi.structure.compose;

import com.example.design.shejimoshi.structure.compose.repo.DepartmentRepo;
import com.example.design.shejimoshi.structure.compose.repo.EmployeeRepo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Description TODO
 * @date 2022/10/25 14:51
 * @Author liuzhihui
 * @Version 1.0
 */
public class Demo {
    private static final long ORGANIZATION_ROOT_ID = 1001;

    private static final String ORGANIZATION_ROOT_CODE = "code";

    @Autowired
    private DepartmentRepo departmentRepo;

    @Autowired
    private EmployeeRepo employeeRepo;

    public void buildOrganization() {
        Department rootDepartment = new Department(ORGANIZATION_ROOT_ID);

        // 方法一: 如果层级深的话,每层都要查询,可能时间会比较长
        buildOrganization(rootDepartment);

        // 方法二: 给部门表加一个code字段,一级为001 二级为001001，三级为001001001 以此类推，人员中也存储这个code
        // 查询某个部门下的人员时,只需要再人员表, code likeRight '001%', 就能查出当前部门下的所有人员信息
    }

    private void buildOrganization(Department department) {
        // 获取子部门集合
        List<Department> subDepartmentIds = departmentRepo.getSubDepartmentIds(department.getId());
        for (Department department1 : subDepartmentIds) {
            // 将子部门添加到父部门中
            department.addSubNodes(department1);
            buildOrganization(department1);
        }

        // 获取当前部门下的员工
        List<Employee> employees = employeeRepo.getDepartmentEmployeeIds(department.getId());
        for (Employee employee : employees) {
            // 将员工添加到父部门中
            department.addSubNodes(employee);
        }
    }
}
